<?php


namespace App\Http\Controllers\Admin;



use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class LoginController extends CommonController
{
    private static $USER_TABLE='user';
    public function Login(Request $request){
        $roles=[
            'account' => 'required',
            'password' => 'required',

        ];
        $messages = [
            'account.required' => '账号不能为空',
            'password.required' => '密码不能为空',
        ];
        $validator =Validator::make($request->all(),$roles,$messages);
        if ($validator->fails()) {
            return $this->ReturnJson(-1,$validator->errors()->first(),'');
        }
        $is_set=DB::table(self::$USER_TABLE)
            ->where('account','=',$request->get('account'))
            ->where('status','=',0)
            ->where('delete_flag','=',0)
            ->select('salt','password','id')
            ->get()
            ->toArray();
        if (!$is_set){
            return $this->ReturnJson(-1,'账号不存在','');
        }
        $pass='lan'.$request->get('password').$is_set[0]->salt;
        if (password_verify($pass, $is_set[0]->password)){
//            $is_set[0]->id  用户id
            //登陆成功 生成token
            $jwtAuth = JwtAuth::getInstance();
            $token = $jwtAuth->setUid($is_set[0]->id)->encode()->getToken();
//            $rand_str = $this->GetRandStr(8);
//            $token = $rand_str.$request->get('account');
//            $token = password_hash($token,PASSWORD_DEFAULT);
            try {
                DB::beginTransaction();
                $now=date('Y-m-d H:i:s',time());
                DB::table(self::$USER_TABLE)->where('id',$is_set[0]->id)->update(['login_time'=>$now,'token'=>$token,'update_by'=>$is_set[0]->id,'update_time'=>$now]);
                DB::commit();
//                session(['token_salt' => $rand_str]);
//                session(['token' => $token]);
//                session(['user_id' => $is_set[0]->id]);
//                session(['account' => $request->get('account')]);
//                Log::debug('拿到session:---'.Session::get('token'));
                return $this->ReturnJson(200,'登陆成功',['token'=>$token]);
            }catch (\Exception $e){
                return $this->ReturnJson(-1,$e->getMessage(),'');
            }
        }else{
            return $this->ReturnJson(-1,'账号或密码错误','');
        }

    }
    public function getUserInfo(Request $request){
        $res=$request->get('token');
        if (!$res){
            return $this->ReturnJson(-1,'参数错误','');
        }
        $info = DB::table(self::$USER_TABLE)
            ->where('delete_flag','=',0)
            ->where('status','=',0)
            ->where('token','=',$res)
            ->select('id','account','ava_url','info')
            ->get();
        $info[0]->roles=$this->GetPermissionInfo($info[0]->id);

        return $this->ReturnJson(200,'success',$info);
    }

    public function GetPermissionInfo($id){
//        $id= $request->get('id');
        $res= $this->GetPermissionUser($id);
        if (!empty($res)){
            foreach ($res as $k=>$v) {
                $arr=['title'=>$v->per_title,'icon'=>$v->per_icon];
                $v->meta=$arr;
            }
        }
        $res=$this->PermissionTree($res);
        return $res;
    }
    public function PermissionTree($data,$pid = 0){
        $children = [];   // 定义存储子级数据数组
        foreach ($data as $key => $value) {
            if ($value->p_id == $pid) {
                unset($data->$key);  // 使用过后可以销毁
                $value->children = $this->PermissionTree($data,$value->per_id);   // 递归调用，查找当前数据的子级
                $children[] = $value;   // 把子级数据添加进数组
            }
        }
        return $children;
    }

    public function LoginOut(){
        Cache::flush();
        return $this->ReturnJson(-2,'验证过期请重新登陆','验证过期请重新登陆');
    }


}
